package top.zlhy7.service;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.MutablePair;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Objects;

/**
 * @author 任勇
 * @date 2021/12/23 8:39
 * @description 爬取漫话
 */
@Slf4j
@Service
public class CrawlComicService {

    @Autowired
    private RestTemplate restTemplate;

    public String chrome() throws Exception {
        //谷歌浏览器驱动所在位置
        System.setProperty("webdriver.chrome.driver", "D:/Program Files/defaultPath/chromedriver.exe");
        //谷歌浏览器所在位置
        System.setProperty("webdriver.chrome.bin", "C:/Program Files/Google/Chrome/Application/chrome.exe");
        ChromeOptions chromeOptions = new ChromeOptions();
        //开启则不打开窗口运行
        //chromeOptions.addArguments("--headless");
        //chromeOptions.addArguments("--no-sandbox");
        //downloadFile(richPagesList.get(i).getAttribute("src"),String.format("%s/%s/%03d.jpg",downloadPath,mutablePair.getLeft(),i));
        WebDriver webDriver = new ChromeDriver(chromeOptions);

        webDriver.get("https://guimanhua.com/page/3/");

        List<MutablePair<String, String>> urlSourceList = 获取所有漫话链接(webDriver,1);
        for (MutablePair<String, String> mutablePair : urlSourceList) {
            下载漫话(webDriver,mutablePair);
        }
        return "chrome";
    }

    /**
     * 只获取前5页所有漫话
     * @param webDriver
     * @return
     */
    public List<MutablePair<String, String>> 获取所有漫话链接(WebDriver webDriver,int limitPage) throws Exception{
        //<title,url>
        List<MutablePair<String, String>> list = new ArrayList<>();
        String url = null;
        for (int i = 1; i < limitPage+1; i++) {
            url = String.format("http://guimanhua.com/page/%d/",i);
            log.info("访问url:{}",url);
            webDriver.get(url);
            Thread.sleep(800);
            //获取所有标题
            List<WebElement> entryTitleList = webDriver.findElements(By.className("entry-title"));
            //所有链接
            List<WebElement> entryPermalinkList = webDriver.findElements(By.className("entry-permalink"));
            //获取所有链接
            for (int j = 0; j < entryTitleList.size(); j++) {
                MutablePair<String, String> mutablePair = MutablePair.of(entryTitleList.get(j).getText(), entryPermalinkList.get(j).getAttribute("href"));
                log.info("title:{},url:{}",mutablePair.getLeft(),mutablePair.getRight());
                list.add(mutablePair);
            }
        }
        return list;
    }

    /**
     *
     * @param mutablePair <title,url>
     */
    public void 下载漫话(WebDriver webDriver,MutablePair<String, String> mutablePair){
        webDriver.get(mutablePair.getRight());
        //创建本地目录用户保存
        String downloadPath = "D:\\ryProject\\selenium\\demo\\src\\test\\kbmh\\";
        if(StringUtils.isBlank(mutablePair.getLeft())){
            //补齐缺失漫话名
            mutablePair.setLeft(webDriver.findElement(By.id("activity-name")).getText());
        }
        File filePath =new File( downloadPath+mutablePair.getLeft());
        //创建存放漫话的目录
        filePath.mkdirs();
        List<WebElement> richPagesList = webDriver.findElements(By.className("rich_pages"));
        if(CollectionUtils.isEmpty(richPagesList)){
            return;
        }
        //第一个是推荐图片，因此跳过
        for (int i = 1; i < richPagesList.size(); i++) {
            log.info("正在下载漫画 {}，第 {}/{}页",mutablePair.getLeft(),i,richPagesList.size());
            downloadFile(richPagesList.get(i).getAttribute("src"),String.format("%s/%s/%03d.jpg",downloadPath,mutablePair.getLeft(),i));
        }
        log.info("漫画 {} 下载完毕",mutablePair.getLeft());
    }
    /**
     * 下载文件
     * @return
     * @author 任勇 on 2021/11/5 18:27
     */
    public File downloadFile(String url,String imgFilePath){
        if(url.startsWith("data")){
            //base64图片
            Base64ToImage(url,imgFilePath);
            return null;
        }
        try {
            ResponseEntity<byte[]> responseEntity = restTemplate.getForEntity(url, byte[].class);
            Files.write(Paths.get(imgFilePath), Objects.requireNonNull(responseEntity.getBody()));
            return new File(imgFilePath);
        } catch (Exception e) {
            log.error("下载对比文档失败,下载地址：{}，错误信息：{}",url,e.getMessage());
        }
        return null;
    }

    /**
     * 将base64解码成图片并保存在传入的路径下
     * 第一个参数为base64 ，第二个参数为路径
     *
     * @param base64, imgFilePath
     * @return boolean
     */
    public static boolean Base64ToImage(String base64, String imgFilePath) {
        // 对字节数组字符串进行Base64解码并生成图片
        if (StringUtils.isEmpty(base64)){
            return false;
        }
        try (OutputStream out = new FileOutputStream(imgFilePath)){
            // Base64解码
            byte[] b = Base64.getDecoder().decode(base64);
            for (int i = 0; i < b.length; i++) {
                // 调整异常数据
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            out.write(b);
            out.flush();
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
